<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
	<title>Home</title>
	<script src="/resources/static/js/jquery.min.js" type="text/javascript" charset="utf-8"></script>
	<script src="http://static.opentok.com/v0.91/js/TB.min.js" type="text/javascript" charset="utf-8"></script>
	<script type="text/javascript" charset="utf-8">
	var sessionData;
	var session;
	function createSession(){
		jQuery.ajax({
			url: '/createSession',
			type: 'GET',
			success: function (data){
				sessionData = data;
				alert('in test'+sessionData.sessionId);
				if(sessionData != null && sessionData != 'undefined'){
					//document.write(sessionData.sessionId);
					 session = TB.initSession(sessionData.sessionId);			
				     session.addEventListener('sessionConnected', sessionConnectedHandler);
					  session.addEventListener('streamCreated', streamCreatedHandler);
				     TB.addEventListener("exception", exceptionHandler);
				     TB.setLogLevel(TB.DEBUG);
				     session.connect(sessionData.apiKey, sessionData.token);
				}
			}
		});		
	}
	
	function sessionConnectedHandler(event){
			alert("in session connected handler");
			 var publishProps = {height:240, width:320};
		      publisher = TB.initPublisher(sessionData.apiKey, 'sessionDiv', publishProps);
		      // Send my stream to the session
		      session.publish(publisher);
		      var subscriberLink = "http://"+window.document.location.host+"/nexus-1.0.0-BUILD-SNAPSHOT/subscribe?sessionId="+sessionData.sessionId+"&token="+sessionData.token;
		      $('#subscriberDiv').html("Share the below link to invite to session <br>" +subscriberLink);
	}
	
	function subscribeToStreams(streams) {
	      for (var i = 0; i < streams.length; i++) {
	        // Make sure we don't subscribe to ourself
	        if (streams[i].connection.connectionId == session.connection.connectionId) {
	          return;
	        }
	        var div = document.createElement('div');
	        div.setAttribute('id', 'stream' + streams[i].streamId);
	        document.body.appendChild(div);

	        // Subscribe to the stream
	        var subscribeProps = {height:240, width:320};
	        session.subscribe(streams[i], div.id);
			 $('#publisherDiv').html("");
	      }
	    }
	
	function streamCreatedHandler(event) {
	      // Subscribe to any new streams that are created
		  alert('in stream created handler');
	      subscribeToStreams(event.streams);
	    }
	function exceptionHandler(event){
		 TB.log(event.message);
		alert('in exception event');
	}
	
	
	
	
	</script>
</head>
<body>
Click below button to start sharing.<br>

<input type="button" onclick="createSession()" name="createSession" id="createSession" value="Start Session"/>


<div id="sessionDiv">
</div>
<div id="subscriberDiv">
</div>
</body>
</html>
